{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>运单管理系统</title>
    <link href="{% static 'plugins/bootstrap-5.3.0-alpha1-dist/css/bootstrap.min.css' %}" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons @1.10.0/font/bootstrap-icons.css">
    <!-- 引入 Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js "></script>

    <style>
        :root {
            --primary-color: #4361ee;
            --primary-light: #eef2ff;
            --secondary-color: #3f37c9;
            --accent-color: #4895ef;
            --success-color: #4cc9f0;
            --text-primary: #2b2d42;
            --text-secondary: #6c757d;
            --bg-light: #f8f9fa;
            --border-color: #e9ecef;
        }
        body {
            background-color: #f8fafc;
            font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
            color: var(--text-primary);
        }
        .page-header {
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--border-color);
        }
        .page-header h4 {
            font-weight: 600;
            color: var(--primary-color);
        }
        .search-container {
            background-color: #fff;
            padding: 1.25rem;
            border-radius: 0.75rem;
            box-shadow: 0 2px 12px rgba(0,0,0,0.03);
            margin-bottom: 1.5rem;
            border: 1px solid var(--border-color);
        }
        .shipment-card {
            display: none; /* 默认隐藏 */
            margin-bottom: 1.5rem;
        }
        .chart-container {
            max-height: 400px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="container py-4">
    <div class="row">
        <div class="col-12">
            <div class="page-header">
                <h4 class="text-center">工厂运单分析报表</h4>
            </div>

            <!-- 搜索区域 -->
            <div class="search-container">
                <div class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label small text-muted">工厂名称</label>
                        <input type="text" class="form-control" id="searchPlate" placeholder="工厂名称">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small text-muted">物品名称</label>
                        <input type="text" class="form-control" id="searchItemName" placeholder="输入物品名称">
                    </div>
                    <div class="col-md-3">
                        <div class="form-check mt-4">
                            <input type="checkbox" class="form-check-input" id="searchZeroShipment">
                            <label class="form-check-label" for="searchZeroShipment">
                                仅显示实际发货量为0
                            </label>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="btn-group w-100">
                            <button type="button" class="btn btn-primary" id="searchButton">
                                <i class="bi bi-search me-1"></i> 查询
                            </button>
                            <button type="button" class="btn btn-light" id="resetButton">
                                <i class="bi bi-arrow-counterclockwise me-1"></i> 重置
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 数据展示 -->
            <div id="shipmentContainer">
                {% for group in grouped_data %}
                <div class="card shipment-card">
                    <div class="card-header bg-primary text-white">
                        <h5><i class="bi bi-building me-2"></i>工厂：{{ group.plate }}</h5>
                    </div>

                    <!-- 饼图区域 -->
                    <div class="card-body chart-container">
                        <canvas class="shipment-pie-chart" height="100"></canvas>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>物品名称</th>
                                    <th>计划发运量</th>
                                    <th>实际发货量</th>
                                    <th>未发货数量</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for item in group.items %}
                                <tr>
                                    <td>{{ item.物品名称 }}</td>
                                    <td>{{ item.计划发运量|default:"0" }}</td>
                                    <td>{{ item.发货数量|default:"0" }}</td>
                                    <td>{{ item.未发货数量|default:"0" }}</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                            <tfoot>
                                <tr class="footer-row">
                                    <td><strong>合计</strong></td>
                                    <td class="total-plan"><strong>0</strong></td>
                                    <td class="total-ship"><strong>0</strong></td>
                                    <td class="total-unshipped"><strong>0</strong></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
                {% endfor %}
            </div>

            <!-- 分页导航 -->
            <nav aria-label="Page navigation" class="my-4">
                <ul class="pagination justify-content-center" id="paginationULBottom"></ul>
            </nav>
        </div>
    </div>
</div>

<!-- 引入 JS -->
<script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-5.3.0-alpha1-dist/js/bootstrap.bundle.min.js' %}"></script>

<script>
$(document).ready(function () {
    const itemsPerPage = 5;
    let currentPage = 1;
    let totalPages = 1;
    const $cards = $('.shipment-card');

    function initPagination() {
        totalPages = Math.ceil($cards.filter(':visible').length / itemsPerPage);
        updatePagination();
        showPage(currentPage);
    }

    function updatePagination() {
        $('#paginationULBottom').empty();
        if (totalPages <= 1) return;

        $('#paginationULBottom').append(`
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="prev">«</a>
            </li>
        `);

        for (let i = 1; i <= totalPages; i++) {
            $('#paginationULBottom').append(`
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
        }

        $('#paginationULBottom').append(`
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="next">»</a>
            </li>
        `);
    }

    function showPage(page) {
        const visibleCards = $cards.filter(':visible');
        totalPages = Math.ceil(visibleCards.length / itemsPerPage);
        currentPage = Math.max(1, Math.min(page, totalPages));
        const start = (currentPage - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        $cards.hide();
        visibleCards.slice(start, end).show();
        updatePagination();
    }

    function calculateTotals() {
        $('.shipment-card').each(function () {
            const $card = $(this);
            let totalPlan = 0, totalShip = 0, totalUnshipped = 0;
            $card.find('tbody tr:visible').each(function () {
                const plan = parseInt($(this).find('td:eq(1)').text()) || 0;
                const ship = parseInt($(this).find('td:eq(2)').text()) || 0;
                const unshipped = plan - ship;
                totalPlan += plan;
                totalShip += ship;
                totalUnshipped += unshipped;
            });
            $card.find('.total-plan strong').text(totalPlan);
            $card.find('.total-ship strong').text(totalShip);
            $card.find('.total-unshipped strong').text(totalUnshipped);
        });
    }

    // 渲染每个工厂的饼图（按物品分类）
    function renderFactoryPieCharts() {
    $('.shipment-card').each(function () {
        const $card = $(this);
        const $canvas = $card.find('.shipment-pie-chart');

        let totalShipped = 0;
        let totalUnshipped = 0;

        // 遍历当前工厂下所有可见行
        $card.find('tbody tr:visible').each(function () {
            const shipped = parseInt($(this).find('td:eq(2)').text()) || 0;
            const planned = parseInt($(this).find('td:eq(1)').text()) || 0;
            const unshipped = planned - shipped;

            totalShipped += shipped;
            totalUnshipped += unshipped;
        });

        // 如果没有数据，不绘制图表
        if (totalShipped === 0 && totalUnshipped === 0) {
            if ($canvas.data('chart')) {
                $canvas.data('chart').destroy();
            }
            return;
        }

        // 销毁旧图表实例
        if ($canvas.data('chart')){
            $canvas.data('chart').destroy();
        }

        const ctx = $canvas[0].getContext('2d');
        const chart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: ['已发货', '未发货'],
                datasets: [{
                    label: '发货统计',
                    data: [totalShipped, totalUnshipped],
                    backgroundColor: ['#4cc9f0', '#ff7f50'], // 蓝色、橙色
                    hoverOffset: 10,
                    borderRadius: 5
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            boxWidth: 12,
                            padding: 12
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `${context.label}: ${context.raw} 单`;
                            }
                        }
                    },
                    title: { display: false }
                }
            }
        });

        $canvas.data('chart', chart);
    });
}

    function performSearch() {
        const plateFilter = $('#searchPlate').val().toLowerCase().trim();
        const itemFilter = $('#searchItemName').val().toLowerCase().trim();
        const showZeroOnly = $('#searchZeroShipment').prop('checked');

        $('.shipment-card').each(function () {
            const $card = $(this);
            const factoryName = $card.find('.card-header h5')
                .text()
                .replace('工厂：', '')
                .toLowerCase()
                .trim();

            const matchFactory = !plateFilter || factoryName.includes(plateFilter);
            if (!matchFactory) {
                $card.hide();
                return;
            }

            let hasMatch = false;
            $card.find('tbody tr').each(function () {
                const $row = $(this);
                const itemName = $row.find('td:eq(0)').text().toLowerCase();
                const shipQty = parseFloat($row.find('td:eq(2)').text()) || 0;
                const matchItem = !itemFilter || itemName.includes(itemFilter);
                const matchQty = !showZeroOnly || shipQty === 0;
                const rowMatch = matchItem && matchQty;
                $row.toggle(rowMatch);
                if (rowMatch) hasMatch = true;
            });

            $card.toggle(hasMatch);
        });

        calculateTotals();
        initPagination();
        renderFactoryPieCharts(); // 更新饼图
    }

    function resetSearch() {
        $('#searchPlate, #searchItemName').val('');
        $('#searchZeroShipment').prop('checked', false);
        $('.shipment-card').show();
        $('.shipment-card tbody tr').show();
        calculateTotals();
        initPagination();
        renderFactoryPieCharts(); // 重置饼图
    }

    $(function () {
        $('.shipment-card').show();
        calculateTotals();
        initPagination();
        renderFactoryPieCharts(); // 初始加载饼图
    });

    $('#searchButton').on('click', performSearch);
    $('#resetButton').on('click', resetSearch);

    $(document).on('click', '.page-link', function (e) {
        e.preventDefault();
        const action = $(this).data('page');
        if (action === 'prev') {
            showPage(currentPage - 1);
        } else if (action === 'next') {
            showPage(currentPage + 1);
        } else if (typeof action === 'number') {
            showPage(action);
        }
    });
});
</script>
</body>
</html>